<template>
  <div class="uploder">
    <el-upload action="" :show-file-list="false" :multiple="true" accept="upload.accept" :limit="100"
               :on-exceed="onExceed" :http-request="doUpload">
      <slot><a class="el-button el-button--warning"><i class="el-icon-upload2"></i><span>上传</span></a></slot>
    </el-upload>
    <div class="upload-dialog">
      <transition name="el-fade-in-linear">
        <el-dialog title="文件上传进度" :visible.sync="showProgress" :modal="false" top="0vh"
                   :close-on-click-modal="false">
          <div class="upload-dialog--file" v-for="file in files" :key="file.id">
            <span>{{ file.name }}</span>
            <el-progress :percentage="file.percent" :status="file.status"></el-progress>
          </div>
        </el-dialog>
      </transition>
    </div>
  </div>
</template>

<script>
  import Http from "axios";
  import {env} from "../../env";
  import Size from "@/ui/common/mixins/size";

  export default {
	name: "uploder",
	mixins: [Size],
	data() {
	  return {
		showProgress: false,
		files: [],
		upload: {
		  action: '/api/admin/datas/upload',
		  accept: '.dat',
		},
	  }
	},
	mounted() {
	  this.$on("_upload:end", () => {
		this.$emit('upload:end', true)
	  });
	},
	methods: {
	  onExceed: function () {
		this.$message.error("最多同时上传100个文件!");
	  },
	  doUpload: function (file) {
		this.showProgress = true;
		this.files.push({
		  id: file.file.uid,
		  name: file.file.name,
		  percent: 0
		});
		var ossData = new FormData();
		ossData.append("file", file.file);
		Http.post((env.VUE_APP_BASE_URL.startsWith('/') ? location.origin : env.VUE_APP_BASE_URL) + this.upload.action, ossData, {
		  timeout: 1000 * 60 * 60,
		  headers: {"Content-Type": "multipart/form-data;"},
		  onUploadProgress: progress => {
			var percent = parseInt(((progress.loaded / progress.total) * 100) | 0);
			this.doShowProgress(file, percent);
		  }
		}).then(() => {
		  this.doUploadResult(file, true);
		}).catch(() => {
		  this.doUploadResult(file, false);
		});
	  },
	  doShowProgress: function (file, percent) {
		this.$set(this.files.filter(f => f.id === file.file.uid)[0], "percent", percent);
	  },
	  doUploadResult: function (file, state) {
		this.$set(this.files.filter(f => f.id === file.file.uid)[0], "status", state ? "success" : "exception");
		setTimeout(() => {
		  this.endUpload(file, state);
		}, 1000);
	  },
	  endUpload: function (file) {
		var index = -1;
		this.files.forEach((f, i) => {
		  if (f.id === file.file.uid) {
			index = i;
		  }
		});
		this.files.splice(index, 1);
		if (this.files.length == 0) {
		  this.showProgress = false;
		  this.$emit("_upload:end", true);
		}
	  }
	}
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  @require "../../ui/common/stylus/variable.styl"
  .uploder {
    display inline-block;
  }
</style>